/*
*  Copyright 2019-2023 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.system.rest;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import me.zhengjie.annotation.Log;
import me.zhengjie.modules.system.domain.*;
import me.zhengjie.modules.system.domain.dto.TeskandreadDto;
import me.zhengjie.modules.system.service.*;
import me.zhengjie.modules.system.domain.vo.TeskQueryCriteria;
import lombok.RequiredArgsConstructor;

import java.sql.Timestamp;
import java.util.*;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
* @author shitou
* @date 2024-05-23
**/
@RestController
@RequiredArgsConstructor
@Api(tags = "任务管理")
@RequestMapping("/api/tesk")
public class TeskController {

    private final TeskService teskService;

    private final ClazzandteskService clazzandteskService;

    private final TeskandmessageService teskandmessageService;

    private final TeskandreadService teskandreadService;

    private final TeskandresourceService teskandresourceService;

    private final TeskandactiveService teskandactiveService;

    private final ClazzandstudentService clazzandstudentService;

    private final StudentService studentService;

    private final TeskAndstudentService teskAndstudentService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('tesk:list')")
    public void exportTesk(HttpServletResponse response, TeskQueryCriteria criteria) throws IOException {
        teskService.download(teskService.queryAll(criteria), response);
    }

    @GetMapping
    @Log("查询任务")
    @ApiOperation("查询任务")
//    @PreAuthorize("@el.check('tesk:list')")
    public ResponseEntity<List<Tesk>> queryTesk(TeskQueryCriteria criteria, Page<Object> page){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clazzId",criteria.getClazzId());
        List<Clazzandtesk>  list = clazzandteskService.list(queryWrapper);

        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("clazzId",criteria.getClazzId());
        Long size = clazzandstudentService.count(queryWrapper1);

        QueryWrapper queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("clazzId",criteria.getClazzId());
        List<Clazzandstudent> clazzandstudentList = clazzandstudentService.list(queryWrapper1);
        List<Integer> studetnIds = new ArrayList<>();
        for(Clazzandstudent item:clazzandstudentList){
            if(item.getUserId()!=null){
                studetnIds.add(Math.toIntExact(item.getUserId()));
            }

        }

        List<TeskAndstudent> teskAndstudentList = new ArrayList<>();
        if(studetnIds.size()>0){

            QueryWrapper queryWrapper3 = new QueryWrapper<>();
            queryWrapper3.in("userId",studetnIds);
            teskAndstudentList = teskAndstudentService.list(queryWrapper3);
        }

        List<Integer> teskIds = new ArrayList<>();


        if(!list.isEmpty()){

            for(Clazzandtesk clazzandtesk : list){
                teskIds.add(clazzandtesk.getTeskid());
            }

        }
        if(!teskIds.isEmpty()){

            List<Tesk> teskList = teskService.listByIds(teskIds);

            for(Tesk tesk:teskList){
                tesk.setContent(String.valueOf(size));
                Integer currentSize = 0;

                for(TeskAndstudent teskAndstudent :teskAndstudentList){
                    if(tesk.getId().equals(teskAndstudent.getTeskId()) && teskAndstudent.getState()!=null && teskAndstudent.getState() == 1){
                        currentSize = currentSize + 1;
                    }
                }
                tesk.setStudentCount(Math.toIntExact(size));
                tesk.setCompletedCount(currentSize);
            }
            return new ResponseEntity<>(teskList,HttpStatus.OK);
        } else {
            return null;
        }

    }
    @GetMapping("/queryTeskMsg")
    @Log("查询任务详情")
    @ApiOperation("查询任务详情")
    public ResponseEntity<Tesk> queryTeskMsg(@RequestParam("id") String teskId){

        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",teskId);

        Tesk tesk = teskService.getOne(queryWrapper);
        if(tesk.getType() == 0){

            QueryWrapper queryWrapperMsg = new QueryWrapper<>();
            queryWrapperMsg.eq("teskId",teskId);
            Teskandmessage teskandmessage = teskandmessageService.getOne(queryWrapperMsg);
            tesk.setContent(teskandmessage.getContent());

        } else if(tesk.getType() == 1){

            QueryWrapper queryWrapperMsg = new QueryWrapper<>();
            queryWrapperMsg.eq("teskId",teskId);
            List<Teskandread>  teskandreadList = teskandreadService.list(queryWrapperMsg);

            List<TeskandreadDto> teachArr = new ArrayList<>();

            for(Teskandread item:teskandreadList){
                List<Integer> teachChapterArr  = new ArrayList<>();
                List<Integer> teachSubsectionArr  = new ArrayList<>();
                if(item.getTeachChapterId()!=null){
                    teachChapterArr.add(item.getTeachChapterId());

                }
                if(item.getTeachSubsectionId()!=null){
                    teachSubsectionArr.add(item.getTeachSubsectionId());
                }

                if(teachArr.size() == 0){

                    TeskandreadDto teskandreadDto = new TeskandreadDto();
                    teskandreadDto.setTeachId(item.getTeachid());


                    teskandreadDto.setTeachChapterArr(teachChapterArr);
                    teskandreadDto.setTeachSubsectionArr(teachSubsectionArr);

                    teachArr.add(teskandreadDto);
                } else {
                    Integer status = 0;
                    for(TeskandreadDto item1:teachArr){
                        if(Objects.equals(item1.getTeachId(), item.getTeachid())){
                            status = 1;

                            List<Integer> currentTeachChapterArr = new ArrayList<>();
                            Collections.addAll(currentTeachChapterArr, teachChapterArr.toArray(new Integer[0]));
                            Collections.addAll(currentTeachChapterArr, item1.getTeachChapterArr().toArray(new Integer[0]));

                            List<Integer> currentteachSubsectionArr = new ArrayList<>();
                            Collections.addAll(currentteachSubsectionArr, teachSubsectionArr.toArray(new Integer[0]));
                            Collections.addAll(currentteachSubsectionArr, item1.getTeachSubsectionArr().toArray(new Integer[0]));

                            item1.setTeachChapterArr(currentTeachChapterArr);
                            item1.setTeachSubsectionArr(currentteachSubsectionArr);
                        }
                    }
                    if(status == 0){
                        TeskandreadDto teskandreadDto = new TeskandreadDto();
                        teskandreadDto.setTeachId(item.getTeachid());
                        teachChapterArr.add(item.getTeachChapterId());
                        teachSubsectionArr.add(item.getTeachSubsectionId());

                        teskandreadDto.setTeachChapterArr(teachChapterArr);
                        teskandreadDto.setTeachSubsectionArr(teachSubsectionArr);

                        teachArr.add(teskandreadDto);
                    }
                }
            }
            tesk.setTeachArrId(teachArr);

        } else if(tesk.getType() == 2){

            QueryWrapper queryWrapperMsg = new QueryWrapper<>();
            queryWrapperMsg.eq("teskId",teskId);
            List<Teskandresource> teskandresourceList = teskandresourceService.list(queryWrapperMsg);

            List<String> ids = new ArrayList<>();
            for(Teskandresource item:teskandresourceList){
                ids.add(item.getResourceid());
            }
            tesk.setResourceArrId(ids);
        } else {
            QueryWrapper queryWrapperMsg = new QueryWrapper<>();
            queryWrapperMsg.eq("teskId",teskId);
            List<Teskandactive> teskandactiveList = teskandactiveService.list(queryWrapperMsg);
            List<Integer> ids = new ArrayList<>();
            for(Teskandactive item:teskandactiveList){
                ids.add(item.getExercisesetid());
            }
            tesk.setExerciseSetArrId(ids);
        }
        QueryWrapper queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("teskId",tesk.getId());
        List<Clazzandtesk> clazzandteskList = clazzandteskService.list(queryWrapper1);
        List<Integer> clazzandteskIds = new ArrayList<>();
        for(Clazzandtesk item:clazzandteskList){
            clazzandteskIds.add(item.getClazzid());
        }
        tesk.setClazzIds(clazzandteskIds);
        return new ResponseEntity<>(tesk,HttpStatus.OK);
    }

    @PostMapping
    @Log("新增任务")
    @ApiOperation("新增任务")
    public ResponseEntity<Object> createTesk(@Validated @RequestBody Tesk resources){
        if(resources.getClazzIds().isEmpty()){
            return null;
        }
        Tesk tesk = JSON.parseObject(JSON.toJSONString(resources), Tesk.class);
        long currentTimeMillis = System.currentTimeMillis();
        Timestamp currentTimestamp = new Timestamp(currentTimeMillis);
        if(tesk.getId()!=null){
            tesk.setCreateBy(currentTimestamp);
            teskService.update(tesk);
        } else {
            tesk.setCreateBy(currentTimestamp);
            teskService.create(tesk);
        }

        //每个班级绑定任务

        if(resources.getClazzIds()!=null && resources.getClazzIds().size()>0){

            QueryWrapper queryWrapperSutdentAndClazz = new QueryWrapper<>();
            queryWrapperSutdentAndClazz.in("clazzId",resources.getClazzIds());
            List<Clazzandstudent> studentandclassList = clazzandstudentService.list(queryWrapperSutdentAndClazz);

            List<Long> studentIds = new ArrayList<>();
            for(Clazzandstudent studentandclass : studentandclassList){
                studentIds.add(studentandclass.getStudentId());
            }
            if(studentIds!=null && studentIds.size() == 0){
                return new ResponseEntity<>("班级学生存在空",HttpStatus.NOT_FOUND);
            }

            for(Integer clazzId : resources.getClazzIds()){
                Clazzandtesk clazzandtesk = new Clazzandtesk();
                clazzandtesk.setClazzid(clazzId);
                clazzandtesk.setTeskid(tesk.getId());
                clazzandteskService.create(clazzandtesk);
            }





            QueryWrapper studentQueryWrapper = new QueryWrapper<>();
            studentQueryWrapper.in("id",studentIds);
            List<Student> studentList = studentService.list(studentQueryWrapper);
            QueryWrapper teskStudentWrapper = new QueryWrapper<>();
            teskStudentWrapper.eq("teskId",tesk.getId());
            teskAndstudentService.remove(teskStudentWrapper);
            for(Student student: studentList){
                TeskAndstudent teskAndstudent = new TeskAndstudent();
                teskAndstudent.setTeskId(tesk.getId());
                teskAndstudent.setStudentId(Math.toIntExact(student.getId()));
                teskAndstudent.setUserId(Math.toIntExact(student.getUserid()));
                teskAndstudentService.save(teskAndstudent);
            }
        }


        if(tesk.getType() == 0){ //消息通知
            Map<String, Object> current = new HashMap<>();
            current.put("teskId",tesk.getId());
            teskandmessageService.removeByMap(current);
            Teskandmessage teskandmessage = new Teskandmessage();
            teskandmessage.setTeskid(tesk.getId());
            teskandmessage.setContent(resources.getContent());
            teskandmessageService.create(teskandmessage);

        } else if(tesk.getType() == 1){ //教材阅读
            Map<String, Object> current = new HashMap<>();
            current.put("teskId",tesk.getId());

            teskandreadService.removeByMap(current);
            for(TeskandreadDto item:resources.getTeachArrId()){
                for(Integer item1:item.getTeachChapterArr()){
                    Teskandread teskandread = new Teskandread();
                    teskandread.setTeskid(tesk.getId());
                    teskandread.setCourseid(resources.getCourseId());
                    teskandread.setTeachid(item.getTeachId());
                    teskandread.setTeachChapterId(item1);
                    teskandreadService.create(teskandread);
                }

                for(Integer item1:item.getTeachSubsectionArr()){
                    Teskandread teskandread = new Teskandread();
                    teskandread.setTeskid(tesk.getId());
                    teskandread.setCourseid(resources.getCourseId());
                    teskandread.setTeachid(item.getTeachId());
                    teskandread.setTeachSubsectionId(item1);
                    teskandreadService.create(teskandread);
                }
            }

        } else if(tesk.getType() == 2){ //资源学习
            Map<String, Object> current = new HashMap<>();
            current.put("teskId",tesk.getId());
            teskandresourceService.removeByMap(current);
            for(String item:resources.getResourceArrId()){
                Teskandresource teskandresource = new Teskandresource();
                teskandresource.setTeskid(tesk.getId());
                teskandresource.setResourceid(item);
                teskandresourceService.create(teskandresource);
            }

        } else if(tesk.getType() == 3){ //教学活动
            Map<String, Object> current = new HashMap<>();
            current.put("teskId",tesk.getId());
            teskandactiveService.removeByMap(current);
            for(Integer item:tesk.getExerciseSetArrId()){
                Teskandactive teskandactive = new Teskandactive();
                teskandactive.setTeskid(tesk.getId());
                teskandactive.setExercisesetid(item);
                teskandactive.setType(0);
                teskandactiveService.create(teskandactive);
            }

        }
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改任务")
    @ApiOperation("修改任务")
//    @PreAuthorize("@el.check('tesk:edit')")
    public ResponseEntity<Object> updateTesk(@Validated @RequestBody Tesk resources){
//        if(!resources.getClazzIds().isEmpty()){
//            return null;
//        }
//        Tesk tesk = JSON.parseObject(JSON.toJSONString(resources), Tesk.class);
//        teskService.update(tesk);
//        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("clazzId", tesk.getId());
//        List<Clazzandtesk> clazzandteskList = clazzandteskService.list(queryWrapper);
//        List<Integer> oldclazzIds = new ArrayList<>();
//        for(Clazzandtesk clazzandtesk : clazzandteskList){
//            oldclazzIds.add(clazzandtesk.getClazzid());
//        }
//
//        //循环出新加入的班级id
//        List<Integer> clazzIds = new ArrayList<>();
//        List<Integer> newclazzIds = new ArrayList<>();
//        for(Integer clazzId : resources.getClazzIds()){
//            if(!containsElement(oldclazzIds,clazzId)){
//                clazzIds.add(clazzId);
//            }
//            newclazzIds.add(clazzId);
//        }
//        //添加加入的班级
//        if(!clazzIds.isEmpty()){
//            for(Integer clazzId : clazzIds){
//                Clazzandtesk clazzandtesk = new Clazzandtesk();
//                clazzandtesk.setClazzid(clazzId);
//                clazzandtesk.setTeskid(tesk.getId());
//                clazzandteskService.create(clazzandtesk);
//            }
//        }
//        List<Integer> delclazzIds = new ArrayList<>();
//        //获取删除的班级id
//        for(Integer clazzId : oldclazzIds){
//            if(!containsElement(newclazzIds,clazzId)){
//                delclazzIds.add(clazzId);
//            }
//        }
//        if(!delclazzIds.isEmpty()){
//            for(Integer clazzId : clazzIds){
//                QueryWrapper queryWrapper1 = new QueryWrapper<>();
//                queryWrapper1.eq("clazzId", clazzId);
//                queryWrapper1.eq("teskId", tesk.getId());
//                clazzandteskService.remove(queryWrapper1);
//            }
//        }

        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    public boolean containsElement(List<Integer> array, Integer target) {
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i) ==  target) {
                return true;
            }
        }
        return false;
    }

    @DeleteMapping
    @Log("删除任务")
    @ApiOperation("删除任务")
//    @PreAuthorize("@el.check('tesk:del')")
    public ResponseEntity<Object> deleteTesk(@RequestBody List<Integer> ids) {
        teskService.deleteAll(ids);

        List<Tesk>  teskList = teskService.listByIds(ids);

        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        List<Integer> list3 = new ArrayList<>();
        List<Integer> list4 = new ArrayList<>();

        for(Tesk item:teskList){
            if(item.getType() == 0){
                list1.add(item.getId());
            } else if(item.getType() == 1){
                list2.add(item.getId());
            } else if(item.getType() == 2){
                list3.add(item.getId());
            } else if(item.getType() == 3){
                list4.add(item.getId());
            }
        }
        if(list1.size()!=0){

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("teskId",list1);
            teskandmessageService.remove(queryWrapper);

        } else if(list2.size()!=0){

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("teskId",list1);
            teskandreadService.remove(queryWrapper);

        } else if(list3.size()!=0){

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("teskId",list1);
            teskandresourceService.remove(queryWrapper);

        } else if(list4.size()!=0){

            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.in("teskId",list1);
            teskandactiveService.remove(queryWrapper);

        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}